package com.pointcircle.core.web.auth;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pointcircle.core.FrameworkConstant;
import com.pointcircle.core.entity.User;
import com.pointcircle.core.repository.UserRepository;
import com.pointcircle.core.service.PropertyService;
import com.pointcircle.core.util.JwtUtils;
import com.pointcircle.core.util.RestResponseUtils;
import com.pointcircle.core.web.RestResponse;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("auth/form")
@Slf4j
public class FormApi {
	@Autowired
	private PropertyService propertyService;
	
	@Autowired
	private UserRepository userRepository;
	
	@Getter
	@Setter
	public static class LoginForm {
		private String username;
		private String password;
	}
	
	@PostMapping("login")
	public RestResponse login(@RequestBody LoginForm loginForm) {
		try {
			String username = loginForm.getUsername();
			String password = loginForm.getPassword();
			SimpleHash simpleHash = new SimpleHash("sha-1", password);
			simpleHash.setIterations(1);
			String passwordHex = simpleHash.toHex();
			User user = userRepository.findByUsername(username);
			if(user == null || !StringUtils.equals(user.getPasswordHex(), passwordHex)) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.username-or-password-wrong")
				);
			}
			String jwtToken = JwtUtils.sign(user.getId(), user.getPasswordHex());
			RestResponseAuthInfo res = new RestResponseAuthInfo(jwtToken, user);
			return res;
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			RestResponse res = RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_LOGIN_FAIL, e.getMessage());
			return res;
		}
	}
}
